/**
 * Generate code from /{{projectName}}-core/src/main/java/{{packageName}}/core/{{modules}}/service/impl/{{entities@SQL}}ServiceImpl.java.hbs
 */
// @SkipOverwrite
package cn.ibizlab.core.authorization.service.impl;

import cn.ibizlab.core.authorization.domain.SysGrantedAuthority;
import cn.ibizlab.core.authorization.domain.SysRole;
import cn.ibizlab.core.authorization.domain.SysRoleMember;
import cn.ibizlab.core.authorization.filter.SysRoleSearchContext;
import cn.ibizlab.util.enums.Entities;
import cn.ibizlab.util.errors.BadRequestAlertException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 实体[系统角色] 服务对象接口实现
 */
@Slf4j
@Service("SysRoleService")
public class SysRoleServiceImpl extends AbstractSysRoleService {

    private static final String SRF_KEY = "srfkey";

    @Override
    @Cacheable(value = "sysrole", key = "'dc:'+#p0.dc")
    public List<SysRole> all(SysRole dto) {
        return this.listDefault(new SysRoleSearchContext());
    }

    @Override
    @Caching(evict = {
            @CacheEvict(value = "sysrole", key = "'dc:'+#p0.dc"),
            @CacheEvict(value = "sysrole", key = "'dc:'"),
            @CacheEvict(value = "sysrole", key = "'dc:null'"),
            @CacheEvict(value = "sysrole", key = "'row:'+#p0.id")
    })
    public boolean create(SysRole et) {
        fillParentData(et);
        if(ObjectUtils.isEmpty(et.getId()))
            et.setId((String)et.getDefaultKey(true));
        this.execute("delete from sys_role where enabled=0 and id = '"+et.getId()+"'",null);
        return super.create(et);
    }

    @Override
    @Caching(evict = {
            @CacheEvict(value = "sysrole", key = "'dc:'+#p0.dc"),
            @CacheEvict(value = "sysrole", key = "'dc:'"),
            @CacheEvict(value = "sysrole", key = "'dc:null'"),
            @CacheEvict(value = "sysrole", key = "'row:'+#p0.id")
    })
    public boolean update(SysRole et) {
        if(et.getGrantedAuthorities()!=null) {
            et.getGrantedAuthorities().forEach(item->item.setRoleId(et.getId()).setId((String)item.getDefaultKey(true)));
        }
        return super.update(et);
    }

    @Override
    @CacheEvict(value = "sysrole", allEntries = true)
    public boolean remove(SysRole et) {
        String key = et.getId();
        SysRole check =  this.getById(key);
        if(check!=null && check.getWorkflowGroup() !=null && check.getWorkflowGroup() ==1)
            throw new BadRequestAlertException("工作流角色不允许删除", Entities.SYS_ROLE.toString(),key);

        if(check!=null && check.getSystemId()!=null && check.getAuthority()!=null
                && (check.getAuthority().equals(String.format("ROLE_%1$s_ADMIN",check.getSystemId().toUpperCase()))
                    ||check.getAuthority().equals(String.format("ROLE_%1$s_USERS",check.getSystemId().toUpperCase()))
                    ||check.getAuthority().equals("ROLE_USERS")
                    ||check.getAuthority().equals("ROLE_SUPERADMIN")
                    ||check.getAuthority().equals("ROLE_APIUSERS")))
            throw new BadRequestAlertException("预定义角色不允许删除", Entities.SYS_ROLE.toString(),key);

        return super.remove(et);
    }

    @Override
    public SysRole personAuth(SysRole dto) {
        List<Map<String,Object>> srfActionParams = dto.getOrDefault("srfactionparam",new ArrayList<>());
        if(!srfActionParams.isEmpty()){
            srfActionParams.forEach(param->
                sysRoleMemberService.save(new SysRoleMember()
                        .setRoleId(dto.getId())
                        .setMemberType((String)param.get("srfdatatype"))
                        .setMemberUid((String)param.get(SRF_KEY)))
            );
        }
        return super.personAuth(dto);
    }

    @Override
    public SysRole permissionAuth(SysRole dto) {
        List<Map<String,Object>> srfActionParams = dto.getOrDefault("srfactionparam",new ArrayList<>());
        if(!srfActionParams.isEmpty()){
            List<SysGrantedAuthority> authorities = new ArrayList<>();
            srfActionParams.forEach(param->
                authorities.add(new SysGrantedAuthority()
                        .setRoleId(dto.getId())
                        .setAuthority((String)param.get(SRF_KEY))
                        .setDisplayName((String)param.get(SRF_KEY))
                        .setPermissionType((String)param.get("type")))
            );
            sysGrantedAuthorityService.saveBatch(authorities);
        }
        return super.permissionAuth(dto);
    }

    @Override
    @Caching(evict = {
            @CacheEvict(value = "sysrole", key = "'dc:'+#p0.dc"),
            @CacheEvict(value = "sysrole", key = "'dc:'"),
            @CacheEvict(value = "sysrole", key = "'dc:null'"),
            @CacheEvict(value = "sysrole", key = "'row:'+#p0.id")
    })
    public SysRole cacheEvict(SysRole dto) {
        return super.cacheEvict(dto);
    }
}